﻿using System;
using System.Collections.Generic;
using System.Text;
using SocialExplorer.IO.FastDBF;
using System.IO;

namespace Soil
{
    /// <summary>
    /// soil components
    /// </summary>
    class SoilComponent
    {
        public SoilComponent(DbfRecord cmpRecord)
        {
            _id = cmpRecord["POLY_ID"];
            _soil_id = cmpRecord["SOIL_ID"];
            _percent = double.Parse(cmpRecord["PERCENT"]) / 100.0; //convert to percent

            _province = cmpRecord["PROVINCE"];
            _soil_code = cmpRecord["SOIL_CODE"];
            _modifer = cmpRecord["MODIFIER"];
            _profile = cmpRecord["PROFILE"];
            _id_code = _province + _soil_code;
            _id_modifer = _id_code + _modifer;
        }

        public SoilComponent(string soilID, double percent)
        {
            _soil_id = soilID;
            _percent = percent;
        }

        private string _id = "";
        private string _soil_id = "";
        private Soil _soil = null;
        private double _percent = 1.0;

        private string _province;
        private string _soil_code;
        private string _modifer;
        private string _profile;
        private string _id_code;
        private string _id_modifer;

        public Soil Soil { get { return _soil; } set { _soil = value; } }
        public string POLY_ID { get { return _id; } }
        public string SOIL_ID { get { return _soil_id; } }
        public string ID_CODE { get { return _id_code; } }
        public string ID_MODIFER { get { return _id_modifer; } }
        public double Percent { get { return _percent; } set { _percent = value; } }

        public override string ToString()
        {
            return _soil_id + "_" + _percent.ToString();
        }

        public SoilComponent Clone()
        {
            return this.MemberwiseClone() as SoilComponent;
        }

        /// <summary>
        /// Merge with other soil component to get a new component
        /// </summary>
        /// <param name="comp"></param>
        /// <returns></returns>
        public SoilComponent Merge(SoilComponent comp)
        {
            SoilComponent newComp = this.Clone();
            newComp.Percent = Percent + comp.Percent;

            if (comp == null) return newComp;
            if (this.Equals(comp)) return newComp;            
            if (Soil != null && comp.Soil == null) return newComp;
            if (Soil == null && comp.Soil == null) return newComp;
            if (Soil == null && comp.Soil != null)
            {
                newComp = comp.Clone();
                newComp.Percent = Percent + comp.Percent;
                return newComp;
            }

            //creat new merged soil component
            Soil mergedSoil = Soil.Merge(comp.Soil, Percent, comp.Percent);
            newComp.Soil = mergedSoil;

            return newComp;
        }
    }
}
